import React, { useState, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import s from './style.module.css';
import Table from '@knownsec/react-component/dist/Table';
import {
	portCol,
	httpCol,
	httpMap,
	jobCol,
	portRemoveCol,
	portAddCol,
	subRemoveCol,
	subAddCol,
} from '../../../JobManage/WebTask/TaskDetail/columns';
import EmptyData from '../../../../components/empty/EmptyData';
import { Menu, Dropdown } from 'antd';
import fetchFer from 'API/fetch';
import Select from '@knownsec/react-component/dist/Select';
import Message from '@knownsec/react-component/dist/Message';
import Button from '@knownsec/react-component/dist/Button';
import { turnToUrlparam } from '../../../../helpers/getUrlParams';
import { datetime, timeChange } from '../../../../../common/formatter';
function Change({ row, hisChangeTaskId }) {
	const [selVal, setSelVal] = useState([]);
	const [selPort, setSelPort] = useState();
	const [selSub, setSelSubl] = useState();
	const [changeInfo, setChangeInfo] = useState(null);
	const [allData, setAllData] = useState(null);
	const [timeOpt, setTimeOpt] = useState([]);
	const [tableLoading, setTableLoading] = React.useState(false);

	useMemo(async () => {
		const res = await fetchFer(
			`/api/v2/repodatas/task_completed_times?job_id=${row.job_id}&task_types=asset`,
			{
				method: 'GET',
			}
		).catch(() => {
			return { data: [] };
		});
		const time = res?.data?.map(e => {
			const differenceTime = Date.now() - new Date(datetime(e.time)).getTime();
			return {
				label: datetime(e.time) +
				`（${timeChange(differenceTime)}前）`,
				labelHtml: `<p style="display:flex"><span style="width: 150px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">${datetime(
					e.time
				)}</span>
        <span style="width: 90px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">（${timeChange(
					differenceTime
				)}前）</span></p>`,
				value: e.id,
				type: e.trigger_type,
			};
		});
		setTimeOpt(time);
		const _selVal = row.task?.task_id || hisChangeTaskId;
		_selVal ? setSelVal([_selVal]) : setSelVal([time[0].value]);
	}, []);
	useEffect(() => {
		getChangeInfo();
	}, [selVal]);
	const getChangeInfo = async () => {
		if (!selVal[0]) return false
		setTableLoading(true);
		const sendData = {
			task_id: selVal[0],
			job_id: row.job_id,
		};
		const params = turnToUrlparam(sendData);
		const info = await fetchFer(`/api/v2/tasks/asset/detail/change?${params}`, {
			method: 'GET',
		}).catch(error => {
			return null;
		});
		const resInfo = {
			port: [...info.results.port.add, ...info.results.port.remove],
			domain: [...info.results.subdomain.add, ...info.results.subdomain.remove],
		};
		setChangeInfo(resInfo || {});
		setAllData(resInfo || {});
		setTableLoading(false);
	};
	const changeSel = (type, value) => {
		if (value) {
			const aa = allData[type].filter(e => {
				return e.detail.op === value;
			});
			setChangeInfo({ ...changeInfo, [type]: aa });
		} else {
			setChangeInfo({ ...changeInfo, [type]: allData[type] });
		}
	};
	return (
		<div>
			{timeOpt.length > 0 && (
				<div className={s.selBox}>
					查看历史结果
					<Select
						pro
						value={selVal}
						placeholder="检测历史"
						option={timeOpt}
						searchable
						className={cn(s.sel)}
						getPopupContainer={triggerNode => triggerNode}
						onChange={({ selectedItem }) => {
							setSelVal([selectedItem[0].value]);
						}}
					/>
				</div>
			)}
			<div className={s.pageLabel}>
				<p>
					端口变动
					{changeInfo?.port.length > 0 && `（${changeInfo?.port.length}）`}
				</p>
				<Select
					pro
					value={selPort}
					placeholder="状态"
					option={[
						{ label: '开启', value: 'add' },
						{ label: '关闭', value: 'remove' },
					]}
					clearable
					className={cn(s.sel)}
					getPopupContainer={triggerNode => triggerNode}
					onChange={({ selectedItem }) => {
						const value = selectedItem[0] ? [selectedItem[0].value] : [];
						setSelPort(value);
						changeSel('port', value[0]);
					}}
				/>
			</div>
			<div className={s.row}>
				<div className={cn(s.mr20)}>
					<Table
						key={'portAdd'}
						loading={tableLoading}
						columns={portAddCol(changeInfo?.port?.add?.length)}
						pro
						scroll={{
							y: 235,
						}}
						className={s.mh240}
						empty={<EmptyData className={s.nobor} type="img"  text={row?.task?.asset_result_id && timeOpt?.length === 0 ? '任务数据已过期，您可重新下发监测任务' : '暂无数据'} />}
						data={(changeInfo?.port || []).map(item => {
							const obj = { add: '开启', remove: '关闭' };
							return {
								...item,
								key: item.id,
								isResolvedIcon: (
									<span className={cn(s.cp)}>{obj[item.detail.op]}</span>
								),
							};
						})}
					/>
				</div>
			</div>
			<div className={s.pageLabel}>
				<p>
					子域名变动
					{changeInfo?.domain.length > 0 && `（${changeInfo?.domain.length}）`}
				</p>
				<Select
					pro
					value={selSub}
					placeholder="状态"
					option={[
						{ label: '上线', value: 'add' },
						{ label: '下线', value: 'remove' },
					]}
					clearable
					className={cn(s.sel)}
					getPopupContainer={triggerNode => triggerNode}
					onChange={({ selectedItem }) => {
						const value = selectedItem[0] ? [selectedItem[0].value] : [];
						setSelSubl(value);
						changeSel('domain', value[0]);
					}}
				/>
			</div>
			<div className={s.row}>
				<div className={cn(s.mr20)}>
					<Table
						loading={tableLoading}
						key={'subAdd'}
						columns={subAddCol()}
						pro
						scroll={{
							y: 235,
						}}
						empty={<EmptyData className={s.nobor} type="img" text={row?.task?.asset_result_id && timeOpt?.length === 0 ? '任务数据已过期，您可重新下发监测任务' : '暂无数据'} />}
						data={(changeInfo?.domain || []).map(item => {
							const obj = { add: '上线', remove: '下线' };
							return {
								...item,
								key: item.id,
								isResolvedIcon: (
									<span className={cn(s.cp)}>{obj[item.detail.op]}</span>
								),
							};
						})}
					/>
				</div>
			</div>
		</div>
	);
}
Change.propTypes = {
	row: PropTypes.any,
	hisChangeTaskId: PropTypes.any,
};
export default Change;
